﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Diagnostics;
using System.Linq;
using System.ServiceProcess;
using System.Text;
using System.IO;
namespace RestSmsServer
{
    public partial class RestSmsServer : ServiceBase
    {
        public RestSmsServer()
        {
            InitializeComponent();
        }

        protected override void OnStart(string[] args)
        {
            writelog("服务程序已启动成功！");
            System.Timers.Timer t = new System.Timers.Timer(10 * 1000);//10秒
            t.Elapsed += new System.Timers.ElapsedEventHandler(TimerEvent_LSX);
            t.AutoReset = true;
            t.Enabled = true;
        }

        protected override void OnStop()
        {
            writelog("服务异常终止，请检查！");
        }
        public void TimerEvent_LSX(object source, System.Timers.ElapsedEventArgs e)
        {
            StartService("SmsServer");
        }
        private void writelog(string readme)
        {
            string Currpath = AppDomain.CurrentDomain.BaseDirectory;
            StreamWriter log = new StreamWriter(Currpath+"RestSmsServer.log",true);
            log.WriteLine(DateTime.Now.ToString("yyy-MM-dd HH:mm:ss") + ":" + readme);
            log.Close();
        }
        private void StartService(string serviceName)
        {
            try
            {
                    System.ServiceProcess.ServiceController service = new System.ServiceProcess.ServiceController(serviceName);
                    if (service.Status == System.ServiceProcess.ServiceControllerStatus.Stopped)
                    {
                        service.Start();
                        for (int i = 0; i < 60; i++)
                        {
                            service.Refresh();
                            System.Threading.Thread.Sleep(1000);
                            if (service.Status == System.ServiceProcess.ServiceControllerStatus.Running)
                            {
                                writelog(serviceName + "启动成功！"+"重试次数"+i);
                                break;
                            }
                            else 
                            {                                   
                                service.Start();
                            }
                        }
                    }
                
            }
            catch (System.Exception ex)
            {
                writelog(ex.Message.ToString());
            }
        }

    }
}
